package com.zhuangfei.hpuhelper.view;

import java.io.File;
import java.util.List;

import cn.lzf.serviceplatform.R;

import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.service.LoginService;
import com.hpu.tools.ShareTools;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ImageUtil;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.FileTools;
import com.zhuangfei.toolkit.IntentToolkit;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ScanActivity extends FragmentActivity {

    private CaptureFragment captureFragment;
    LoginService loginService;
    private LinearLayout backLayout;
    private LinearLayout localLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        initView();
        initEvent();
        ShareTools.put(this, "course_update", 1);
    }

    private void initEvent() {
        backLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ActivityTools.toBackActivityAnim(ScanActivity.this, MenuActivity.class);
            }
        });

        localLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                openImage();
            }
        });
    }

    private void initView() {
        backLayout = (LinearLayout) findViewById(R.id.id_back);
        localLayout = (LinearLayout) findViewById(R.id.id_scan_local);

        loginService = new LoginService(this, handler);

        captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.view_scan_mycamera);
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.view_scan_mycamera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_my_container, captureFragment).commit();
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent data) {
        if (arg0 == 10) {
            if (data != null) {
                Uri uri = data.getData();
                ContentResolver cr = getContentResolver();
                try {
//                	Bitmap mBitmap = MediaStore.Images.Media.getBitmap(cr, uri);//显得到bitmap图片
//                	File file=FileTools.saveViewImage(mBitmap,"codeimg_"+System.currentTimeMillis()+".png");
//                    System.out.println(file.getAbsolutePath());
                    CodeUtils.analyzeBitmap(ImageUtil.getImageAbsolutePath(this, uri), new CodeUtils.AnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                            analyzeResult(result);
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            Toast.makeText(ScanActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                        }
                    });
//                    if (mBitmap != null) {
//                        mBitmap.recycle();
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected void analyzeResult(String result) {
        if (result.startsWith("http")) {
            new IntentToolkit().with(this)
                    .target(WebViewActivity.class)
                    .put("title", "扫描结果")
                    .put("url", result)
                    .execute();
        } else if (result.startsWith("$course$")) {
            result = result.substring(8, result.length());
            ActivityTools.toActivityAnimByExtras(ScanActivity.this, ImportCourseActivity.class, "id", result);
            finish();
        }
        //LOGIN WEB
        else {
            String number = ShareTools.get(ScanActivity.this, ShareConstants.STORE_USER, "").toString();
            String vpnPw = ShareTools.get(ScanActivity.this, ShareConstants.STORE_PASSWORD1, "").toString();
            String jwPw = ShareTools.get(ScanActivity.this, ShareConstants.STORE_PASSWORD2, "").toString();
            loginService.loginWeb(number, vpnPw, jwPw, result);
        }
    }

    public void openImage() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, 10);
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            analyzeResult(result);

        }

        @Override
        public void onAnalyzeFailed() {
            Toast.makeText(ScanActivity.this, "识别失败", Toast.LENGTH_SHORT)
                    .show();
            ActivityTools.toBackActivityAnim(ScanActivity.this,
                    MenuActivity.class);
        }
    };

    public void onBackPressed() {
        ActivityTools.toBackActivityAnim(ScanActivity.this, MenuActivity.class);
    }

    ;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case HttpConstants.SCAN_SUCCESS:
                    Toast.makeText(ScanActivity.this, "登录成功", Toast.LENGTH_SHORT)
                            .show();

                    break;
                case HttpConstants.SCAN_KEY_ERROR:
                    Toast.makeText(ScanActivity.this, "key错误", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case HttpConstants.SCAN_ERROR:
                    Toast.makeText(ScanActivity.this, "登录失败", Toast.LENGTH_SHORT)
                            .show();
                    break;

                default:
                    break;
            }
            ActivityTools.toBackActivityAnim(ScanActivity.this,
                    MenuActivity.class);
        }

        ;
    };
}
